package tbs.framework.xxl.impls;

import com.alibaba.fastjson2.JSON;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.jetbrains.annotations.NotNull;
import tbs.framework.async.container.IAsyncTaskBroker;
import tbs.framework.async.container.IAsyncTaskContainer;
import tbs.framework.async.container.IAsyncTaskService;
import tbs.framework.async.container.model.AsyncTaskDetail;
import tbs.framework.async.task.container.AbstractAsyncTaskService;
import tbs.framework.xxl.model.AsyncTaskInvokeModel;

import java.time.Duration;
import java.util.Optional;

/**
 * @author abstergo
 */
public class XxlJobAsyncTaskService extends AbstractAsyncTaskService {

    private IAsyncTaskService asyncTaskService;

    public XxlJobAsyncTaskService(@NotNull IAsyncTaskContainer container, @NotNull IAsyncTaskBroker asyncTaskExecutor) {
        super(container, asyncTaskExecutor, Duration.ZERO);
        this.asyncTaskService = this;
    }

    @XxlJob("asyncTaskInvoke")
    @Override
    public void service() {
        try {
            final AsyncTaskInvokeModel invokeModel =
                JSON.parseObject(XxlJobHelper.getJobParam(), AsyncTaskInvokeModel.class);
            AsyncTaskDetail asyncTaskDetail =
                Optional.ofNullable(asyncTaskService.container().getTaskDetail(invokeModel.getTaskId()))
                    .orElseThrow(() -> new UnsupportedOperationException("任务不存在"));
            asyncTaskService.getAsyncTaskBroker().execute(asyncTaskDetail, this);
            XxlJobHelper.handleSuccess(
                String.format("job %s-%s work done", invokeModel.getTaskId(), XxlJobHelper.getJobId()));
        } catch (Exception e) {
            XxlJobHelper.handleFail(e.getMessage());
        }
    }

    @XxlJob("asyncTasks")
    public void taskList() {
        XxlJobHelper.handleSuccess(JSON.toJSONString(asyncTaskService.container().tasks()));
    }

    @Override
    public void serviceStop() {

    }
}
